package net.JwtDemo.config;

import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.*;
import org.springframework.security.core.*;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class CustomAuthenticationProvider implements AuthenticationProvider {

    private final UserDetailsService userDetailsService;
    private final PasswordEncoder passwordEncoder;
    //private final RiskCheckService riskCheckService; // 自定义风险检查服务

    // 构造器注入
    public CustomAuthenticationProvider(
        @Lazy UserDetailsService userDetailsService,
        PasswordEncoder passwordEncoder
        //RiskCheckService riskCheckService
    ) {
        this.userDetailsService = userDetailsService;
        this.passwordEncoder = passwordEncoder;
        //this.riskCheckService = riskCheckService;
    }

    @Override
    public Authentication authenticate(Authentication auth) throws AuthenticationException {
        String username = auth.getName();
        String rawPassword = auth.getCredentials().toString();
        log.info("CustomAuthenticationProvider.authenticate(username="+username+",password="+rawPassword+")");
        
        // 1. 基础校验
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(rawPassword)) {
            throw new BadCredentialsException("用户名密码不能为空");
        }

        // 2. 风险检查（自定义逻辑）
//        if (riskCheckService.isHighRiskLogin(username)) {
//            throw new AuthenticationServiceException("高风险登录需二次验证");
//        }

        // 3. 加载用户
        UserDetails user = userDetailsService.loadUserByUsername(username);

        // 4. 密码校验
        if (!passwordEncoder.matches(rawPassword, user.getPassword())) {
            throw new BadCredentialsException("密码错误");
        }

        // 5. 附加检查（如账户状态）
        if (!user.isEnabled()) {
            throw new DisabledException("账户已禁用");
        }

        // 6. 返回完全认证的Token
        return new UsernamePasswordAuthenticationToken(
            user, 
            null, // 密码置空
            user.getAuthorities()
        );
    }

    @Override
    public boolean supports(Class<?> authentication) {
        // 指定支持的认证类型
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }
}